using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class DeleteUserCommandHandler : IRequestHandler<DeleteUserCommand, bool>
	{
		private readonly IBaseRepository<User> _userRepo;
		private readonly IBaseRepository<UserRole> _userRoleRepo;

		public DeleteUserCommandHandler(IBaseRepository<User> userRepo, IBaseRepository<UserRole> userRoleRepo)
		{
			_userRepo = userRepo;
			_userRoleRepo = userRoleRepo;
		}

		public async Task<bool> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
		{
			var user = await _userRepo.GetModel(x => 
				x.UserId == request.UserId && !x.IsDeleted);
			
			if (user == null)
			{
				throw new Exception("用户不存在");
			}

			// 逻辑删除用户
			user.IsDeleted = true;
			user.DeletedAt = DateTime.Now;
			user.UpdatedAt = DateTime.Now;
			await _userRepo.UpdateAsync(user);

			// 删除用户角色关联
			var userRoles = _userRoleRepo.GetAll()
				.Where(x => ((UserRole)x).UserId == request.UserId)
				.Select(x => (UserRole)x)
				.ToList();
			
			if (userRoles.Any())
			{
				await _userRoleRepo.DeleteRangeAsync(userRoles);
			}

			return true;
		}
	}
}

